<?php
    include './public/db_object.php';

    if(isset($_POST['uid'])){
        $uid = $_POST['uid'];

        $db = new DB_object(['db_name'=> 'db_shop']);
        $sql = "select * from t_order where uid=".$uid;
        $res = $db->l_select_all($sql);

        if($res == ''){
            echo json_encode(['error'=>2]);
        }else if($res){
            $gids = [];
            //echo '<pre>';
            // 获取到所有商品的gid
            foreach($res as $key=>$val){
                $gids[] = $val['gid'];
            }
            // 拼接成查询语句
            $goods_sql = select_sql($gids);
            // 获取到所有商品
            $goods_res = $db->l_select_all($goods_sql);
            if($goods_res){

                forEach($gids as $key=>$val){
                    // 将数组中的字符串转成数组
                    $gids_arr[] = explode(',', $gids[$key]);
                }
                //var_dump($res);
                foreach($gids_arr as $k1=>$v1){
                    foreach($v1 as $k2=>$v2){
                        foreach($goods_res as $k3=>$v3){
                            if($v2 == $v3['gid']){
                                $res[$k1]['goods'][] = $v3;
                            }
                        }
                    }
                }
                // 响应
                echo json_encode(['error'=>1, 'data'=> $res]);
            }
        }
        
    }


    /**
     * 拼接成查询语句
    */
    function select_sql($arr){

        $str = str_arr($arr);
        $sql = "select * from t_goods where ".$str;
        return $sql;
    }


    /**
     * 将数组中的字符串转成数组
    */
    function str_arr($arr){
        if(!is_array($arr)){
            return false;
        }
        //var_dump($arr);
        forEach($arr as $key=>$val){
            $arr[$key] = explode(',', $arr[$key]);
            //var_dump(explode(',', $arr[$key]));
        }
        return sql_str($arr);
        //echo sql_str($arr);
    }

    /**
     * 拼接条件
    */
    function sql_str($arr){
        if(!is_array($arr)){
            return false;
        }
        $str = '';
        foreach($arr as $key=>$val){
            foreach($val as $k=>$v){
                $str .= 'gid='.$v.' or ';
            }
        }
        return substr($str, 0, -3);
    }

?>